﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using POSSystem.BLL;
using MyGeneration.dOOdads;

namespace WebUI.EditPages
{
    public partial class EditCategory : BasePage
    {
        Categories cat;
        int catId;
        string mode;

        protected void Page_Load(object sender, EventArgs e)
        {
            base.Page_Load(sender, e);

            if(Request.QueryString[KEY] == null)
            {
                CloseDlg(0);
                return;
            }

            if (Request.QueryString[MODE] == null)
            {
                CloseDlg(0);
                return;
            }

            mode = Request.QueryString[MODE];

            if (Request.QueryString[ID] == null && (mode == EDIT_MODE || mode == VIEW_MODE))
            {
                CloseDlg(0);
                return;
            }

            cat = (Categories)Session[Request.QueryString[KEY]];
            string oldFilter = cat.Filter;

            catId = Request.QueryString[ID] != null ? int.Parse(Request.QueryString[ID]) : 0;
            if (mode != ADD_MODE)
                cat.Filter = Categories.ColumnNames.ID + "=" + catId.ToString();
            else
                btnSave.Enabled = false;

            if (!IsPostBack && cat.RowCount > 0 && mode != ADD_MODE)
            {
                editCategory.CategoryName = cat.CategoryName;
                if (!cat.IsColumnNull(Categories.ColumnNames.VisibleToCustomer))
                    editCategory.VisibleToCustomer = cat.VisibleToCustomer;
                if (!cat.IsColumnNull(Categories.ColumnNames.VisibleToCustomer))
                    editCategory.VisibleToCustomer = cat.VisibleToCustomer;
                if (!cat.IsColumnNull(Categories.ColumnNames.IsDealerOnly))
                    editCategory.IsDealerOnly = cat.IsDealerOnly;
            }
            

            cat.Filter = oldFilter;
        }

        public void btnSave_OnClick(Object sender, EventArgs e)
        {
            if (cat != null)
            {
                Save();
            }
        }

        private void Save()
        {
            TransactionMgr tx = TransactionMgr.ThreadTransactionMgr();
            try
            {
                tx.BeginTransaction();
                string oldFilter = cat.Filter;
                if (mode == ADD_MODE)
                {
                    cat.AddNew();
                    cat.BranchID = Branches.CurrentBranchID;
                    if (catId > 0)
                    {
                        cat.ParentID = catId;
                        Categories c = new Categories();
                        c.LoadByPrimaryKey(catId);
                        if (c.RowCount > 0)
                            cat.Level = c.Level + 1;

                    }
                    else
                        cat.Level = 1;
                    cat.Deleted = false;
                }
                else
                {
                    cat.Filter = Categories.ColumnNames.ID + "=" + catId;
                }

                cat.CategoryName = editCategory.CategoryName;
                View_CategoryTree catTree = null;

                if (mode == ADD_MODE)
                    cat.VisibleToCustomer = editCategory.VisibleToCustomer;
                else if (cat.IsColumnNull(Categories.ColumnNames.VisibleToCustomer) ||  cat.VisibleToCustomer != editCategory.VisibleToCustomer)
                {
                    catTree = new View_CategoryTree();
                    catTree.Search("CHARINDEX('/" + cat.s_ID + "/', '/' + " + View_CategoryTree.ColumnNames.IDPath + " + '/', 0) >= 1", "*", "", 0, int.MaxValue);

                    for (int i = 0; i < catTree.RowCount; i++)
                    {
                        string tmpFilter = cat.Filter;
                        cat.Filter = Categories.ColumnNames.ID + "=" + catTree.s_ID;
                        if (cat.RowCount > 0)
                        {
                            cat.VisibleToCustomer = editCategory.VisibleToCustomer;
                            cat.LastModifiedByUser = SessionUser.ID;
                            cat.LastModifiedDate = DateTime.UtcNow.AddHours(SysVars.TimeZone);
                        }
                        cat.Filter = tmpFilter;
                        catTree.MoveNext();
                    }
                }

                if (mode == ADD_MODE)
                    cat.IsDealerOnly = editCategory.IsDealerOnly;
                else if (cat.IsColumnNull(Categories.ColumnNames.IsDealerOnly) || cat.IsDealerOnly != editCategory.IsDealerOnly)
                {
                    if(catTree == null)
                        catTree = new View_CategoryTree();
                    catTree.Search("CHARINDEX('/" + cat.s_ID + "/', '/' + " + View_CategoryTree.ColumnNames.IDPath + " + '/', 0) >= 1", "*", "", 0, int.MaxValue);

                    string strCatIDs = "";

                    for (int i = 0; i < catTree.RowCount; i++)
                    {
                        strCatIDs += catTree.s_ID;
                        if (i < catTree.RowCount - 1)
                            strCatIDs += ",";

                        string tmpFilter = cat.Filter;
                        cat.Filter = Categories.ColumnNames.ID + "=" + catTree.s_ID;
                        if (cat.RowCount > 0)
                        {
                            cat.IsDealerOnly = editCategory.IsDealerOnly;
                            cat.LastModifiedByUser = SessionUser.ID;
                            cat.LastModifiedDate = DateTime.UtcNow.AddHours(SysVars.TimeZone);
                        }
                        cat.Filter = tmpFilter;
                        catTree.MoveNext();
                    }

                    Products p = (Products)Session[Request.QueryString["pkey"]];
                    string oldProductFilter = p.Filter;
                    catTree.Rewind();
                    for (int i = 0; i < catTree.RowCount; i++)
                    {
                        p.Filter = Products.ColumnNames.CategoryID + "=" + catTree.s_ID;
                        if (p.RowCount > 0)
                        {
                            p.Rewind();
                            for (int j = 0; j < p.RowCount; j++)
                            {
                                p.IsDealerOnly = editCategory.IsDealerOnly;
                                p.MoveNext();
                            }
                        }
                        catTree.MoveNext();
                    }

                    p.Save();
                    p.Filter = oldProductFilter;
                }

                cat.Save();

                if (mode == ADD_MODE)
                {
                    cat.StockKey = cat.ID;
                    cat.Save();
                }

                tx.CommitTransaction();
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("window.returnValue={0};", 1), true);
                cat.Filter = oldFilter;
                ((Popup)Master).ShowMessage("Saved");

            }
            catch (Exception ex)
            {
                tx.RollbackTransaction();
                ((Popup)Master).ShowErrorMessage("Error: " + ex.Message);
                ErrorLog.WriteToFile("EditCategory.aspx.cs", "Save", ex.StackTrace);
            }
        }

        public void btnSaveAndClose_OnClick(Object sender, EventArgs e)
        {
            if (cat != null)
            {
                Save();
                CloseDlg(1);
            }
        }
    }
}
